import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart';

import '../model/api_response.dart';
import '../model/post.dart';
import '../model/user.dart';
import '../util/http_client.dart';

class ApiService {
  // GET 示例：获取用户列表
  static Future<ApiResponse<List<User>>> getUsers() async {
    try {
      final response = await HttpClient.get("/users");
      return _parseResponse<List<User>>(response);
    } catch (e) {
      return ApiResponse(
        data: null,
        status: 500,
        message: "Failed to get users: $e",
      );
    }
  }

  // POST 示例：创建用户 - 完整实现
  static Future<ApiResponse<User>> createUser(User user) async {
    try {
      final response = await HttpClient.post(
        "/users",
        body: user.toJson(),
      );

      return _parseResponse<User>(response);
    } catch (e) {
      return ApiResponse(
        data: null,
        status: 500,
        message: "Failed to create user: $e",
      );
    }
  }


  // POST 示例：创建用户 - 完整实现
  static Future<ApiResponse<Post>> createPost(Post post) async {
    try {
      final response = await HttpClient.post(
        "/post",
        body: post.toJson(),
      );

      return _parseResponse<Post>(response);
    } catch (e) {
      return ApiResponse(
        data: null,
        status: 500,
        message: "Failed to create user: $e",
      );
    }
  }

  // 通用解析方法
  static ApiResponse<T> _parseResponse<T>(Response response) {
    try {
      // 解析 JSON
      final dynamic jsonData = jsonDecode(response.body);
      // jsonDecode() 返回 dynamic 类型
      // Dart 无法隐式将 dynamic 转换为 Map<String, dynamic>
      // 根据类型处理
      if (T == List<User>) {
        if (jsonData is List) {
          final data = jsonData
              .map((e) => User.fromJson(e as Map<String, dynamic>))
              .toList() as T;
          // 使用 as 进行显式类型转换
          // 添加类型断言确保数据类型安全
          // .toList() as T
          //在解析嵌套对象时添加显式类型转换
          // 确保每个列表元素都被视为 Map<String, dynamic>

          return ApiResponse<T>(
            data: data,
            status: response.statusCode,
            message: "Success",
          );
        } else {
          throw "Expected list but got ${jsonData.runtimeType}";
        }
      } else if (T == User) {
        if (jsonData is Map<String, dynamic>) {
          final data = User.fromJson(jsonData) as T;
          return ApiResponse<T>(
            data: data,
            status: response.statusCode,
            message: "Success",
          );
        } else {
          throw "Expected map but got ${jsonData.runtimeType}";
        }
      } else {
        throw "Unsupported type: $T";
      }
    } catch (e) {
      // 返回解析错误响应
      return ApiResponse<T>(
        data: null,
        status: response.statusCode,
        message: "JSON parsing error: $e\nResponse body: ${response.body}",
      );
    }
  }
}
